<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Requests\ProductsRequest;
use App\Models\Collect;
use App\Models\Comments;
use App\Models\Products;
use Illuminate\Http\Request;

class ProductsController extends BaseController
{

    /**
     * 商品列表
     */
    public function index(ProductsRequest $request)
    {


        $category_id=$request->input('category_id');
        $product= Products::where('category_id',$category_id)->paginate($request->input('limit',10));
        $collect=Collect::where('users_id',request()->userId)->get()->toArray();
        $collect=array_column($collect,'products_id','products_id');
        foreach($product as &$item){
            if(!empty($collect[$item['id']])){
                $item['collect']=1;
            }else{
                $item['collect']=0;
            }
            if(Comments::where('products_id',$item['id'])->avg('score')){
                $item['score']=round(Comments::where('products_id',$item['id'])->avg('score'),0);
            }else{
                $item['score']=false;
            }
        }
        return $this->success($product);
    }

    /**
     * 商品详情
     */
    public function show($id)
    {

       $data=Products::with(['comment'=>function($query){
            $query->with('user:username,head_pic,id')->paginate(request()->input('limit',3));
            // $query->with('user');
       },'collect'=>function($query){
        $query->where('users_id',request()->userId);
       }])->find($id)->toArray();
       
       
       $count=Comments::where('products_id',$id)->count();
       $data=[
        'data'=>$data,
        'total'=>$count
       ];
       return $this->success($data);
    }


    /**
     * 推荐商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function recommend(Request $request)
    {

        $product= Products::where('status',1)->paginate($request->input('limit',10));
        $collect=Collect::where('users_id',request()->userId)->get()->toArray();
        $collect=array_column($collect,'products_id','products_id');
        foreach($product as &$item){
            if(!empty($collect[$item['id']])){
                $item['collect']=1;
            }else{
                $item['collect']=0; 
            }
            if(Comments::where('products_id',$item['id'])->avg('score')){
                $item['score']=round(Comments::where('products_id',$item['id'])->avg('score'),0);
            }else{
                $item['score']=false;
            }
        }
        return $this->success($product);
    }
}
